package com.store.service.impl;

import com.store.dto.LoginRequest;
import com.store.dto.LoginResponse;
import com.store.entity.User;
import com.store.mapper.UserMapper;
import com.store.service.AuthService;
import com.store.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class AuthServiceImpl implements AuthService {
    private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    @Transactional
    public LoginResponse login(LoginRequest loginRequest) {
        logger.info("开始处理登录请求: username={}", loginRequest.getUsername());

        User user = userMapper.selectByUsername(loginRequest.getUsername());
        if (user == null) {
            logger.warn("用户不存在: username={}", loginRequest.getUsername());
            throw new RuntimeException("用户不存在");
        }

        if (!loginRequest.getPassword().equals(user.getPassword())) {
            logger.warn("密码错误: username={}", loginRequest.getUsername());
            throw new RuntimeException("密码错误");
        }

        // 更新最后登录时间
        userMapper.updateLastLoginTime(user.getId(), LocalDateTime.now());
        logger.info("更新最后登录时间: userId={}, time={}", user.getId(), LocalDateTime.now());

        String token = jwtUtil.generateToken(user.getUsername());
        logger.debug("生成token成功: username={}", user.getUsername());

        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUsername(user.getUsername());
        response.setRole(user.getRole());

        logger.info("登录成功: username={}, role={}", user.getUsername(), user.getRole());
        return response;
    }

    @Override
    public LoginResponse loginone(LoginRequest loginRequest) {
        return null;
    }



    @Override
    @Transactional
    public void register(LoginRequest registerRequest) {
        logger.info("开始处理注册请求: username={}", registerRequest.getUsername());

        User existingUser = userMapper.selectByUsername(registerRequest.getUsername());
        if (existingUser != null) {
            logger.warn("用户名已存在: username={}", registerRequest.getUsername());
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(registerRequest.getPassword());
        user.setRole(registerRequest.getRole() != null ? registerRequest.getRole() : "USER");

        userMapper.insert(user);
        logger.info("注册成功: username={}, role={}", user.getUsername(), user.getRole());
    }
}
